package com.base.self.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.exception.BaseException;
import com.base.mapper.voipmapper.SubscribersMapper;
import com.base.mapper.voipmapper.UserAuthInfoMapper;
import com.base.po.voip.Subscribers;
import com.base.po.voip.UserAuthInfo;
import com.base.result.PageUtils;
import com.base.result.ResponseResult;
import com.base.result.ResponseResultUtils;
import com.base.self.dto.ptTeam.PtTeamWebListDto;
import com.base.self.entity.Ptintegral;
import com.base.self.mapper.PtintegralMapper;
import com.base.self.service.IPtintegralService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.utils.Produce;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Slf4j
@Service
public class PtintegralServiceImpl extends ServiceImpl<PtintegralMapper, Ptintegral> implements IPtintegralService {
    private final SubscribersMapper subscribersMapper;
    private final PtintegralMapper ptintegralMapper;
    private final UserAuthInfoMapper userAuthInfoMapper;

    public PtintegralServiceImpl(SubscribersMapper subscribersMapper, PtintegralMapper ptintegralMapper, UserAuthInfoMapper userAuthInfoMapper) {
        this.subscribersMapper = subscribersMapper;
        this.ptintegralMapper = ptintegralMapper;
        this.userAuthInfoMapper = userAuthInfoMapper;
    }

    @Override
    public BigDecimal getTotalMoneyByUserId(String userId, Integer type) {
        Optional.ofNullable(subscribersMapper.selectByPrimaryKey(userId)).orElseThrow(() -> new BaseException(ResponseResultUtils.getResponseResultF("该用户不存在")));
        BigDecimal add = coutAllByUserId(userId, 1, type);
        BigDecimal del = coutAllByUserId(userId, 0, type);
        return add.subtract(del);
    }

    public BigDecimal coutAllByUserId(String userId, Integer status, Integer type) {
        QueryWrapper<Ptintegral> queryWrapper = new QueryWrapper<Ptintegral>()
                .select("IFNULL(SUM(money),0) as totalMoney")
                .eq("sub", userId)
                .eq(status != null, "status", status)
                .eq(type != null, "type", type);
        Map<String, Object> map = this.getMap(queryWrapper);
        BigDecimal sumCount = (BigDecimal) map.get("totalMoney");
        return sumCount;
    }

    @Override
    public ResponseResult getTotalMoneyResultDetailByUserId(String userId, Integer type, Integer pageNo, Integer pageSize) {
        Optional.ofNullable(subscribersMapper.selectByPrimaryKey(userId)).orElseThrow(() -> new BaseException(ResponseResultUtils.getResponseResultF("该用户不存在")));
        Page<Ptintegral> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Ptintegral> queryWrapper = new QueryWrapper<Ptintegral>()
                .eq("sub", userId)
                .eq(type != null, "type", type)
                .orderByDesc("create_time");
        IPage<Ptintegral> userIPage = baseMapper.selectPage(page, queryWrapper);
        return ResponseResultUtils.getResponseResultDataS(userIPage);
    }

    @Override
    public ResponseResult selectWebList(PtTeamWebListDto ptIntegralDto) {
        String userId = null;
        if (ptIntegralDto.getMobile() != null && Produce.isMobile(ptIntegralDto.getMobile())) {
            userId = Optional.ofNullable(subscribersMapper.selectBySubscribers(ptIntegralDto.getMobile(), null)).orElse(new Subscribers()).getId();
        }
        final String userIdT = userId;
        Integer type = ptIntegralDto.getType();
        Integer status = ptIntegralDto.getStatus();
        final Map<String, Object> data = PageUtils.getDateMapBack(() -> page(PageUtils.getPage(
                new Page<>(), ptIntegralDto.getOffset(), ptIntegralDto.getLimit()),
                new QueryWrapper<Ptintegral>()
                        .eq(userIdT != null, "sub", userIdT)
                        .eq(type != null, "type", type)
                        .eq(status != null, "status", status)),
            page -> {
                List<Ptintegral> lists= page.getRecords();
                lists.forEach(item->{
                   item.setSub(getSubInfo(item.getSub()));
                 });
               return lists;
            }
        );
        return ResponseResultUtils.getResponseResultDataS(data);
    }

    private String getSubInfo(String userId) {
        final String[] result = {"无法查询到用户信息"};
        Optional.ofNullable(subscribersMapper.selectByPrimaryKey(userId)).ifPresent(x->{
                UserAuthInfo userAuthInfo=Optional.ofNullable(userAuthInfoMapper.findUserAuthInfoById(userId)).orElse(new UserAuthInfo());
                String reultMsg=x.getMobile()+Optional.ofNullable(userAuthInfo.getUserRealName()).orElse("该用户未填写真实姓名");
                 result[0] =reultMsg;
        });
       return result[0];

    }


}
